import validator from 'validator';
import { Op } from 'sequelize';
import models from '../../models';
import { QueryWhereConf, AddPermissionClassifyError } from 'definitions/permission-classify';
import { QueryAllConf } from 'definitions/common';

const { AdminPermissionClassify } = models;

export default function (router) {
  /**
   * 获取权限分类列表
   * @param {String} name 权限分类名称
   * @param {String} sort 排序选项，比如 createdAt_DESC
   * @param {Boolean} all 是否查询全部
   * @param {Number} page 查询页数
   * @param {Number} limit 每页限制数
   */
  router.get('/api/admin/permission-classify', async ctx => {
    const { name, sorter, all } = ctx.request.query;
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);

    let whereConf: QueryWhereConf = {};
    if (name) {
      whereConf.name = {
        [Op.like]: `%${name}%`
      };
    }

    // 排序规则
    let order = [['created_at', 'DESC']];
    if (sorter) {
      const sortName = sorter.split('_')[0].replace('createdAt', 'created_at').replace('updatedAt', 'updated_at');
      const sortFunc = sorter.split('_')[1].replace('ascend', 'ASC').replace('descend', 'DESC');
      order = [[sortName, sortFunc]];
    }

    // 是否获取全部数据
    const allConf: QueryAllConf = {};
    if (!all) {
      allConf.offset = (page - 1) * limit;
      allConf.limit = limit;
    }

    const classifies = await AdminPermissionClassify.findAndCountAll({
      ...allConf,
      where: whereConf,
      order: order
    });
    await ctx.json(true, '获取权限分类成功', { total: classifies.count, list: classifies.rows });
  });

  /**
   * 新增权限分类
   * @param {String} name 权限分类名称
   * @param {String} description 权限分类描述
   */
  /**
   * 新增权限分类
   */
  router.post('/api/admin/permission-classify', async ctx => {
    let { name = '', description = '' } = ctx.request.body;
    // 验证参数
    let error: AddPermissionClassifyError = {};
    if (!name || !validator.isLength(name, { min: 2, max: 10 })) error.name = '权限分类名称格式错误';
    if (await AdminPermissionClassify.isRepeat('name', name)) error.name = '权限分类名称重复';
    if (JSON.stringify(error) !== '{}') {
      await ctx.json(false, 'validate-error', error);
      return;
    }

    // 创建权限分类
    const newPermissionClassify = await AdminPermissionClassify.create({
      name,
      description
    });

    if (newPermissionClassify && newPermissionClassify.id) {
      await ctx.json(true, '权限分类创建成功', newPermissionClassify);
    } else {
      await ctx.json(false, '权限分类创建失败');
    }
  });

  /**
   * 修改权限分类
   * @param {String} name 权限分类名称
   * @param {String} description 权限分类描述
   */
  router.put('/api/admin/permission-classify/:id', async ctx => {
    let { name = '', description = '' } = ctx.request.body;
    const permissionClassify_id = ctx.params.id;
    // 验证参数
    let error: AddPermissionClassifyError = {};
    let params: AddPermissionClassifyError = {};
    if (name) {
      if (!validator.isLength(name, { min: 2, max: 10 })) error.name = '权限分类名格式错误';
      if (await AdminPermissionClassify.isRepeat('name', name, 'self')) error.name = '权限分类名重复';
      params.name = name;
    }
    if (description || description === '') {
      params.description = description;
    }
    if (JSON.stringify(error) !== '{}') {
      await ctx.json(false, 'validate-error', error);
      return;
    }

    // 更新权限分类
    const updateResult = await AdminPermissionClassify.update(params, {
      where: { id: permissionClassify_id }
    });
    if (updateResult[0] === 1) {
      await ctx.json(true, '更新权限分类成功');
    } else {
      await ctx.json(false, '更新权限分类失败');
    }
  });

  /**
   * 删除权限分类
   */
  router.delete('/api/admin/permission-classify/:id', async ctx => {
    const { id } = ctx.params;
    // 删除权限分类
    const deleteResult = await AdminPermissionClassify.destroy({ where: { id } });
    // TODO 删除分类下的权限
    if (deleteResult === 1) {
      await ctx.json(true, '删除权限分类成功');
    } else {
      await ctx.json(false, '删除权限分类失败');
    }
  });
}
